<template>
  <PageWrapper contentBackground :contentFullHeight="true">
    <template #headerContent>
      <div style="display: flex; justify-content: center">
        <RadioGroup v-model:value="searchMode" @change="selectSearchType">
          <RadioButton value="common">{{
            t('routes.demo.documentManager.normalSearch')
          }}</RadioButton>
          <RadioButton value="advanced">{{
            t('routes.demo.documentManager.advancedSearch')
          }}</RadioButton>
        </RadioGroup>
      </div>
      <div style="display: flex; justify-content: center; margin-top: 15px">
        <!-- 普通检索 -->
        <InputSearch
          v-model:value="searchValue"
          v-show="searchMode === 'common'"
          :placeholder="t('routes.demo.documentManager.searchByName')"
          :enter-button="t('common.searchText')"
          style="width: 500px"
          @search="commonSearch"
        />
        <!-- 高级检索 -->
        <BasicForm
          style="width: 800px"
          @register="register"
          v-show="searchMode === 'advanced'"
          @submit="submit"
        />
      </div>
    </template>
    <template #default>
      <Row>
        <Col :xs="1" :sm="1" :md="1" :lg="1" :xl="1" />
        <!-- 左侧 -->
        <Col :xs="4" :sm="4" :md="4" :lg="4" :xl="4">
          <Tabs v-model:activeKey="activeKey" @change="selectLeftType">
            <TabPane key="0" :tab="t('routes.demo.documentManager.catalog')">
              <div style="overflow-y: scroll; overflow-x: hidden; height: 600px">
                <Tree :treeData="directoryList" @select="SelectedDirectory" />
              </div>
            </TabPane>
            <TabPane key="1" :tab="t('routes.demo.documentManager.tag')">
              <div style="overflow-y: scroll; overflow-x: hidden; height: 600px">
                <BasicTree
                  :treeData="labelList"
                  :replaceFields="{
                    key: 'labelID',
                    value: 'keyValues',
                    title: 'labelName',
                    children: 'sonlabellist',
                  }"
                  @select="SelectedLabel"
                />
              </div>
            </TabPane>
            <TabPane key="2" :tab="t('routes.demo.documentManager.my')">
              <RadioGroup v-model:value="myBorrow" @change="changeMyGroup">
                <Radio :style="radioStyle" :value="'0'">{{
                  t('routes.demo.documentManager.borrowing')
                }}</Radio>
                <Radio :style="radioStyle" :value="'1'">{{
                  t('routes.demo.documentManager.historyBorrowing')
                }}</Radio>
                <Radio :style="radioStyle" :value="'2'">{{
                  t('routes.demo.documentManager.overdue')
                }}</Radio>
                <Radio :style="radioStyle" :value="'3'">{{
                  t('routes.demo.documentManager.borrowingProcess')
                }}</Radio>
              </RadioGroup>
            </TabPane>
          </Tabs>
        </Col>
        <Col
          :xs="1"
          :sm="1"
          :md="1"
          :lg="1"
          :xl="1"
          style="display: flex; justify-content: center"
        />
        <!-- 右侧 -->
        <Col :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
          <BasicTable @register="registerTable" v-show="selectSearchValue == 'ML'">
            <template #createTime="{ text: createTime }">
              <span>{{ proxy.$filters.filterTime(createTime) }}</span>
            </template>
            <template #lastModifyTime="{ text: lastModifyTime }">
              <span>{{ proxy.$filters.filterTime(lastModifyTime) }}</span>
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    label: t('routes.demo.documentManager.viewProcess'),
                    icon: 'material-symbols:view-comfy-alt-outline',
                    onClick: handleViewTemplate.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.view'),
                    icon: 'ion:eye-outline',
                    onClick: handleView.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey === '2' && myBorrow === '1',
                  },
                  {
                    label: t('routes.demo.documentManager.edit'),
                    icon: 'ion:pencil-outline',
                    onClick: handleEdit.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.borrow'),
                    icon: 'carbon:global-loan-and-trial',
                    onClick: handleBorrow.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey !== '2',
                  },
                  {
                    label: t('routes.demo.documentManager.browse'),
                    icon: 'streamline:programming-browser-search-search-window-glass-app-code-programming-query-find-magnifying-apps',
                    onClick: handleBrowse.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                  {
                    label: t('routes.demo.documentManager.addTag'),
                    icon: 'ion:ios-pricetags-outline',
                    onClick: handleCreatedProperty.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                ]"
              />
            </template>
          </BasicTable>
          <BasicTable @register="registerCommonTable" v-show="selectSearchValue == 'PT'">
            <template #createTime="{ text: createTime }">
              <span>{{ proxy.$filters.filterTime(createTime) }}</span>
            </template>
            <template #lastModifyTime="{ text: lastModifyTime }">
              <span>{{ proxy.$filters.filterTime(lastModifyTime) }}</span>
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    label: t('routes.demo.documentManager.viewProcess'),
                    icon: 'material-symbols:view-comfy-alt-outline',
                    onClick: handleViewTemplate.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.view'),
                    icon: 'ion:eye-outline',
                    onClick: handleView.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey === '2' && myBorrow === '1',
                  },
                  {
                    label: t('routes.demo.documentManager.edit'),
                    icon: 'ion:pencil-outline',
                    onClick: handleEdit.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.borrow'),
                    icon: 'carbon:global-loan-and-trial',
                    onClick: handleBorrow.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey !== '2',
                  },
                  {
                    label: t('routes.demo.documentManager.browse'),
                    icon: 'streamline:programming-browser-search-search-window-glass-app-code-programming-query-find-magnifying-apps',
                    onClick: handleBrowse.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                  {
                    label: t('routes.demo.documentManager.addTag'),
                    icon: 'ion:ios-pricetags-outline',
                    onClick: handleCreatedProperty.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                ]"
              />
            </template>
          </BasicTable>
          <BasicTable @register="registerAdvancedTable" v-show="selectSearchValue == 'GJ'">
            <template #createTime="{ text: createTime }">
              <span>{{ proxy.$filters.filterTime(createTime) }}</span>
            </template>
            <template #lastModifyTime="{ text: lastModifyTime }">
              <span>{{ proxy.$filters.filterTime(lastModifyTime) }}</span>
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    label: t('routes.demo.documentManager.viewProcess'),
                    icon: 'material-symbols:view-comfy-alt-outline',
                    onClick: handleViewTemplate.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.view'),
                    icon: 'ion:eye-outline',
                    onClick: handleView.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey === '2' && myBorrow === '1',
                  },
                  {
                    label: t('routes.demo.documentManager.edit'),
                    icon: 'ion:pencil-outline',
                    onClick: handleEdit.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: false,
                  },
                  {
                    label: t('routes.demo.documentManager.borrow'),
                    icon: 'carbon:global-loan-and-trial',
                    onClick: handleBorrow.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                    ifShow: activeKey !== '2',
                  },
                  {
                    label: t('routes.demo.documentManager.browse'),
                    icon: 'streamline:programming-browser-search-search-window-glass-app-code-programming-query-find-magnifying-apps',
                    onClick: handleBrowse.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                  {
                    label: t('routes.demo.documentManager.addTag'),
                    icon: 'ion:ios-pricetags-outline',
                    onClick: handleCreatedProperty.bind(null, record),
                    // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
                  },
                ]"
              />
            </template>
          </BasicTable>
        </Col>
      </Row>
      <!-- 添加属性弹窗 -->
      <addKeyWordOrLabel
        @register="registerPropertyModal"
        :labelList="labelList"
        @success="dirReload()"
      />
      <!-- 借阅流程 -->
      <selectForm @register="registerBorrowModal" />

      <!-- 修改查看历史借阅审批流程数据 -->
      <viewHistory @register="registerFormModal" />
    </template>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, reactive, getCurrentInstance } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicTree } from '/@/components/Tree/index';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import throttle from 'lodash/throttle';
  import { Base64 } from 'js-base64';

  import { Radio, InputSearch, Row, Col, Tabs, TabPane, Tree } from 'ant-design-vue';
  import { getKnowledgeSearch, getKnowledgeColumns } from './tableData';
  import addKeyWordOrLabel from './addKeyWordOrLabel.vue';
  import selectForm from '../formManager/selectForm.vue';
  import viewHistory from './viewHistory.vue';

  import { getDocLabelApi, getDataDirectoryApi } from '/@/api/demo/flow';
  import {
    getBorrowBdDataAdvancedSelect,
    getBorrowBdDataSelectFile,
    getBorrowBdDataJudge,
  } from '/@/api/demo/knowledge';

  import { browseFile } from '/@/api/demo/document';

  const RadioGroup = Radio.Group;
  const RadioButton = Radio.Button;
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const { proxy }: any = getCurrentInstance();
  const searchMode = ref('common');
  const searchValue = ref('');
  const directory = ref('1');
  const label = ref('');
  const selectType = ref('common');
  // 左侧切换
  const activeKey = ref('0');
  const labelList = ref<any[]>([]);
  const directoryList = ref<any[]>([]);
  const labelParams = {
    LabelName: '',
    Status: '',
  };

  // 我的借阅样式
  const radioStyle = reactive({
    display: 'block',
    height: '30px',
    lineHeight: '30px',
  });
  const myBorrow = ref<string>('0');
  const selectSearchValue = ref<string>('ML'); // PT:普通模式，GJ高级模式

  // 目录列表接口
  getDataDirectoryApi(1).then((res) => {
    directoryList.value = res;
  });

  // 标签列表接口
  getDocLabelApi(labelParams).then((res) => {
    labelList.value = res;
  });

  // 左侧标签切换事件
  const selectLeftType = (activeKey) => {
    // activeKey=0 activeKey=1 activeKey=2 我的
    /* 1.搜索栏恢复默认值（普通搜索）
   2.清空普通搜索框和高级搜索框的值
   3. 调用接口，传值对应目录类型， 对应目录类型id 清空
*/
    if (activeKey === '0') {
      clearActiveKey();
      dirReload();
    } else if (activeKey === '1') {
      clearActiveKey();
    } else if (activeKey === '2') {
      selectSearchValue.value = 'ML';
      clearActiveKey();
      dirReload();
    }
  };
  const clearActiveKey = () => {
    searchMode.value = 'common';
    searchValue.value = '';
    resetFields();
  };

  // 目录选择事件
  const SelectedDirectory = (key) => {
    selectSearchValue.value = 'ML';
    directory.value = key.toString();
    dirReload();
  };

  // 标签选择事件
  const SelectedLabel = (keys) => {
    selectSearchValue.value = 'ML';
    label.value = keys.toString();
    dirReload();
  };

  // 我的选择事件
  const changeMyGroup = (e) => {
    selectSearchValue.value = 'ML';
    myBorrow.value = e.target.value;
    dirReload();
  };

  // 普通、高级检索切换
  const selectSearchType = (type) => {
    selectType.value = type.target.value;
    if (type.target.value === 'common') {
      resetFields();
    } else if (type.target.value === 'advanced') {
      searchValue.value = '';
    }
  };

  const commonSearch = () => {
    selectSearchValue.value = 'PT';
    commonReload();
  };

  const submit = () => {
    selectSearchValue.value = 'GJ';
    advancedReload();
  };

  // 操作点击事件
  const handleBorrow = (record: Recordable) => {
    getBorrowBdDataJudge().then((res) => {
      if (res === '1') {
        if (record.status === '生效') {
          const param = {
            record: record,
            currentDireId:
              activeKey.value === '0'
                ? directory.value
                : activeKey.value === '1'
                ? label.value
                : myBorrow.value,
          };
          openBorrowModal(true, param);
        } else {
          createMessage.error(t('routes.demo.documentManager.onlyBorrowAble'));
        }
      } else {
        const param = {
          record: record,
          currentDireId:
            activeKey.value === '0'
              ? directory.value
              : activeKey.value === '1'
              ? label.value
              : myBorrow.value,
        };
        openBorrowModal(true, param);
      }
    });
  };
  const handleBrowse = throttle((record: Recordable) => {
    browseFile(record.oId, record.canBrowserVision).then((res) => {
      let url = res[0]; //要预览文件的访问地址
      const innerWidth = (window.innerWidth - 1000) / 2;
      const innerHeight = (window.innerHeight - 600) / 2;
      const windowFeatures = `left=${innerWidth},top=${innerHeight},width=1000,height=600`;
      window.open(
        res.data.result[1] + ':8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)),
        'mozillaWindow',
        windowFeatures,
      );
    });
  }, 3000);
  const handleCreatedProperty = (record: Recordable) => {
    openPropertyModal(true, record);
  };
  const handleViewTemplate = (record: Recordable) => {
    console.log('点击了查看模板', record);
  };
  const handleView = (record: Recordable) => {
    openFormModal(true, { record: record, isUpdate: false });
  };
  const handleEdit = (record: Recordable) => {
    openFormModal(true, { record: record, isUpdate: true });
  };

  const [register, { getFieldsValue: getFieldsValue, resetFields }] = useForm({
    schemas: getKnowledgeSearch(),
    labelWidth: 100,
    colon: true,
    actionColOptions: {
      span: 24,
    },
    submitButtonOptions: {
      text: t('common.searchText'),
    },
  });

  // 目录表格
  const [registerTable, { reload: dirReload }] = useTable({
    // 分页配置
    columns: getKnowledgeColumns(),
    api: getBorrowBdDataSelectFile,
    beforeFetch: (params) => {
      params.Type = activeKey.value;
      params.TypeAboutId =
        activeKey.value === '0'
          ? directory.value
          : activeKey.value === '1'
          ? label.value
          : myBorrow.value;
    },
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'items',
      // 接口返回的表格总数字段名称
      totalField: 'totalCount',
    },
    showTableSetting: true, // 显示表格设置工具
    showIndexColumn: false,
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    bordered: true,
    canResize: false,
    actionColumn: {
      width: 300,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 普通搜索表格
  const [registerCommonTable, { reload: commonReload }] = useTable({
    // 分页配置
    columns: getKnowledgeColumns(),
    api: getBorrowBdDataAdvancedSelect,
    beforeFetch: (params) => {
      params.Name = searchValue.value;
      params.ThitObjectId = searchValue.value;
      params.FileName = searchValue.value;
      params.DocLabel = searchValue.value;
      params.Type = activeKey.value;
      params.TypeAboutId =
        activeKey.value === '0'
          ? directory.value
          : activeKey.value === '1'
          ? label.value
          : myBorrow.value;
      params.SelectType = selectType.value === 'common' ? '0' : '1';
    },
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'items',
      // 接口返回的表格总数字段名称
      totalField: 'totalCount',
    },
    showTableSetting: true, // 显示表格设置工具
    showIndexColumn: false,
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    bordered: true,
    canResize: false,
    actionColumn: {
      width: 300,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 高级搜索
  const [registerAdvancedTable, { reload: advancedReload }] = useTable({
    // 分页配置
    columns: getKnowledgeColumns(),
    api: getBorrowBdDataAdvancedSelect,
    beforeFetch: (params) => {
      params.Name = getFieldsValue().Name;
      params.ThitObjectId = getFieldsValue().ThitObjectId;
      params.FileName = getFieldsValue().FileName;
      params.DocLabel = getFieldsValue().DocLabel;
      params.FileType = getFieldsValue().FileType;
      params.SelectStartTime = getFieldsValue().releaseTime ? getFieldsValue().releaseTime[0] : '';
      params.SelectEndTime = getFieldsValue().releaseTime ? getFieldsValue().releaseTime[1] : '';
      params.Type = activeKey.value;
      params.TypeAboutId =
        activeKey.value === '0'
          ? directory.value
          : activeKey.value === '1'
          ? label.value
          : myBorrow.value;
      params.SelectType = selectType.value === 'common' ? '0' : '1';
    },
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'items',
      // 接口返回的表格总数字段名称
      totalField: 'totalCount',
    },
    showTableSetting: true, // 显示表格设置工具
    showIndexColumn: false,
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    bordered: true,
    canResize: false,
    actionColumn: {
      width: 300,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  // 添加属性弹窗
  const [registerPropertyModal, { openModal: openPropertyModal }] = useModal();
  // 借阅流程弹窗
  const [registerBorrowModal, { openModal: openBorrowModal }] = useModal();

  // 查看表格弹窗
  const [registerFormModal, { openModal: openFormModal }] = useModal();
</script>

<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  ::v-deep(.ant-page-header) {
    margin: 16px !important;
  }
</style>
